<template>
  <div id="comments-list">
    <div class="main-floors" v-loading="isLoading">
      <div v-if="!isLoading && !comments.length"
           class="no-data border-top border-bottom">没有评论数据</div>
      <MainFloor v-for="comment in comments" :key="comment.id" :comment="comment"
                 :placement="placement" :placement-id="placementId"/>
    </div>
    <pagination class="m-t-0 m-b-24"
                :current-page="pagination.currentPage" :page-count="pagination.pageCount"/>
    <MainReply :placement="placement" :placement-id="placementId"
                :receive-user-id="placementAuthorId" v-on:commentSuccess="commentSuccess"/>
  </div>
</template>

<script>
import MainFloor from './MainFloor';
import MainReply from './MainReply';
import * as format from './format';

export default {
  name: 'Comments', // 评论区列表
  components: { MainFloor, MainReply },
  props: {
    placement: { // 是哪个位置调用了评论区
      type: String,
      required: true,
    },
    placementId: { // 调用的位置的id
      type: Number,
      required: true,
    },
    placementAuthorId: { // 创建评论后应该给谁提醒
      type: Number,
      required: true,
    },
  },
  data() {
    return {
      comments: [], // 评论列表
      isLoading: false, // 正在加载评论列表
      pagination: { // 翻页组件
        currentPage: null, // 当前页
        pageCount: null, // 总页数
      },
    };
  },
  computed: {
    // 加载评论列表所需参数
    initLoadParams() {
      return {
        placement: this.placement, // 是哪个位置调用了评论区
        placementId: this.placementId, // 调用的位置的id
        page: this.$route.query.page || 1,
      };
    },
  },
  methods: {
    // 加载评论列表
    loadComments() {
      this.isLoading = true;
      this.$api.comments.index(this.initLoadParams)
        .then(res => this.handleRes(res))
        .catch(() => {})
        .then(() => { this.isLoading = false; });
    },
    // 处理返回结果
    handleRes(res) {
      this.comments = format.formatComments(res.data);
      this.pagination.currentPage = res.kaminari.current_page;
      this.pagination.pageCount = res.kaminari.total_pages;
    },
    // 评论成功
    commentSuccess(comment) { this.comments.push(comment); },
  },
  created() { this.loadComments(); },
  watch: {
    initLoadParams(newVal, oldVal) {
      if (JSON.stringify(newVal) !== JSON.stringify(oldVal)) { // 通过url加载楼中楼会导致波动
        this.comments = [];
        this.loadComments();
      }
    },
  },
};
</script>

<style lang="scss">
#comments-list .main-floors {
  min-height: 3rem;
  padding: 1.5rem 0;
}
</style>
